#!/usr/bin/env python

"""
id$ this script is aim to start fcgi
"""
from django.core.servers.fastcgi import runfastcgi
import os
import signal
import sys

sys.path.insert(0,'/infoware/mytest')
os.environ['DJANGO_SETTINGS_MODULE']='settings'

PIDFILE_fmt='/var/run/fcgi/mytest%d.pid'
SOCKET_fmt='/var/run/fcgi/mytest%d.sock'

def get_pidfile(fcgi_id):
    return PIDFILE_fmt%fcgi_id
def get_socket(fcgi_id):
    return SOCKET_fmt%fcgi_id

def start(fcgi_id):
    PIDFILE=get_pidfile(fcgi_id)
    SOCKET=get_socket(fcgi_id)
    if os.path.exists(PIDFILE):
        print 'fcgi%d has already started'%fcgi_id
    else:
        print 'Starting fcgi%d: '%fcgi_id
        runfastcgi(daemonize='true',method='prefork',maxspare=10,minspare=3,maxchildren=10,maxrequests=10,
        socket=SOCKET,pidfile=PIDFILE)
        print 'success'

def stop(fcgi_id):
    PIDFILE=get_pidfile(fcgi_id)
    if os.path.exists(PIDFILE):
        print 'Shutting down fcgi%d'%fcgi_id
        fp=open(PIDFILE)
        try:
            os.kill(int(fp.read()),signal.SIGKILL)
        except:
            pass
        fp.close()
        os.remove( PIDFILE )
    else:
        print 'fcgi%d has not be started, please start first'%fcgi_id

def restart(fcgi_id):
    stop(fcgi_id)
    start(fcgi_id)

def status():
    for fcgi_id in xrange(5):
        PIDFILE=get_pidfile(fcgi_id)
        if os.path.exists(PIDFILE):
            print 'fcgi%d is running'%fcgi_id
        else:
            print 'fcgi%d is not running'%fcgi_id


def usage():
    print 'use like this: %s start|stop|status|restart' %sys.argv[0]


if __name__=='__main__':
    import threading
    if len(sys.argv) != 2:
        usage()
    elif sys.argv[1] == 'start':
        for tid in xrange(5):
            t=threading.Thread(target=start,args=(tid,))
            t.start()
            t.join()

    elif sys.argv[1] == 'stop':
        for tid in xrange(5):
            t=threading.Thread(target=stop,args=(tid,))
            t.start()
            t.join()
    elif sys.argv[1] == 'status':
        status()
    else: usage()

